package org.bw.bookstore.common.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;

public class JwtTokenUtils {
    public static String makeToken(Integer userId, String nickName, String roles) {

        JwtBuilder builder = Jwts.builder();
        builder.setId(String.valueOf(userId));      //设置唯一编号
        builder.setSubject(nickName);               //设置主题  可以是JSON数据
        builder.setIssuedAt(new Date());            //设置签发日期

        // 设置过期时间（24小时）
        long now = System.currentTimeMillis();
        long exp = now+1000*60*60*24;
        builder.setExpiration( new Date( exp ) );

        // 增加角色设置
        builder.claim( "roles",roles );

        // 设置签名 使用HS256算法，并设置SecretKey(字符串)
        builder.signWith(SignatureAlgorithm.HS256, ConstUtils.TOKEN_PASS_WORD);

        // 构建 并返回一个字符串
        String token = builder.compact();
        System.out.println(token);

        return token;
    }

    public static HashMap verifyToken(String token) {
        HashMap<String, Object> resultMap = new HashMap<String, Object>();

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(ConstUtils.TOKEN_PASS_WORD)
                    .parseClaimsJws(token)
                    .getBody();

            System.out.println(claims);
            System.out.println("id=" + claims.getId());
            System.out.println("sub=" + claims.getSubject());
            System.out.println("time=" + claims.getIssuedAt());
            System.out.println("roles=" + claims.get("roles"));

            resultMap.put("userId", claims.getId());
            resultMap.put("userName", claims.getSubject());
            resultMap.put("roles", claims.get("roles"));

        }
        catch (ExpiredJwtException e) {
            System.out.println("token expired");
        } catch (SignatureException e) {
            System.out.println("token signature error");
        } catch (Exception e) {
            System.out.println("token error");
        }

        return resultMap;
    }
}
